package cn.shentianlan.service.impl;

import cn.shentianlan.criteria.ClassCriteria;
import cn.shentianlan.domain.dto.ClassDTO;
import cn.shentianlan.domain.entity.Clazz;
import cn.shentianlan.mapper.ClassMapper;
import cn.shentianlan.service.ClassService;
import cn.shentianlan.utils.BaseUtils;
import cn.shentianlan.utils.DataUtils;
import cn.shentianlan.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 陈俊源
 * @Description TODO
 * @Date 2021/4/18
 * @Version 1.0
 */
@Service
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;

    @Override
    public Result findClassByCriteria(ClassCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(),criteria.getPageSize(),false);
        List<Clazz> clazzList = classMapper.findClassByCriteria(criteria);
        Integer count = classMapper.getCount(criteria);
        List<ClassDTO> classDTOList = new ArrayList<>();
        for (Clazz clazz:clazzList){
            ClassDTO classDTO = buildClassDTO(clazz);
            classDTOList.add(classDTO);
        }
        PageInfo<ClassDTO> pageInfo = new PageInfo<>(classDTOList);
        pageInfo.setTotal(count.longValue());
        return Result.success(pageInfo);
    }

    private ClassDTO buildClassDTO(Clazz clazz) {
        ClassDTO classDTO = BaseUtils.copyProperties(clazz, ClassDTO.class);
        return classDTO;
    }

    @Override
    public Result saveOrUpdateClass(ClassDTO classDTO) {
        Clazz classByName = classMapper.getClassByName(classDTO.getClassName());
        if (classByName!=null){
            return Result.fail("班级已存在，不可重复添加");
        }
        Clazz clazz = BaseUtils.copyProperties(classDTO, Clazz.class);
        if (classDTO.getId() == null){
            clazz.setId(DataUtils.assignId());
            classMapper.saveClass(clazz);
        }else {
            classMapper.updateClass(clazz);
        }
        return Result.success(clazz.getId());
    }

    @Override
    public Result getClassById(Long id) {
        if (id==null){
            return Result.fail("id为空，无法查询到班级信息");
        }
        Clazz clazz = classMapper.getClassById(id);
        if (clazz == null){
            return Result.fail("获取该id对应的班级信息出错");
        }
        return Result.success(clazz);
    }

    @Override
    public Result deleteClassById(Long id) {
        if (id==null){
            return Result.fail("id为空，无法执行删除操作");
        }
        Clazz clazz = classMapper.getClassById(id);
        if (clazz == null){
            return Result.fail("未找到对应的班级信息，删除失败");
        }
        classMapper.deleteClassById(id);
        return Result.success(id);
    }
}
